package edu.zzuli.assistant.service.impl;

import org.apache.commons.mail.SimpleEmail;
import org.hibernate.Session;
import org.hibernate.Transaction;
import edu.zzuli.assistant.bean.FindPsw;
import edu.zzuli.assistant.dao.FindPswDao;
import edu.zzuli.assistant.dao.impl.FindPswDaoImpl;
import edu.zzuli.assistant.service.FindPswService;
import edu.zzuli.assistant.until.HibernateUtil;

public class FindPswServiceImpl implements FindPswService {

	private  FindPswDao findPswDao = new  FindPswDaoImpl();
	@Override
	public boolean add(FindPsw findPsw,String path) {
		// TODO Auto-generated method stub
		Session session = null;
		Transaction tx = null;
		
		boolean result = true;
		if (findPsw.getUserId() != null && findPsw.getEmail() != null
				&& findPsw.getFailTime() != null)
			try {
				session = HibernateUtil.getCurrentSession();
				tx = session.beginTransaction();
				findPswDao.add(findPsw);
				tx.commit();

				SimpleEmail email = new SimpleEmail();
				email.setTLS(true);
				email.setHostName("smtp.163.com");
				email.setAuthentication("IEC_WQ", "zzuli_itstudio"); // 用户名和密码
				email.addTo(findPsw.getEmail());
				email.setFrom("IEC_WQ@163.com"); // 发送方
				email.setSubject("no reply"); // 标题
				String emailContent ="请勿回复本邮件.2小时以内点击下面的链接,重设密码,如非本人操作请忽略此邮件。"+path+"?key="+findPsw.getKey();
				email.setCharset("UTF-8");
				email.setMsg(emailContent); // 内容
				email.send();
			} catch (Exception exception) {
				result = false;
			}finally{
				
				HibernateUtil.closeSession();
			}

		return result;
		
	}

	@Override
	public FindPsw getByKey(String key) {
		// TODO Auto-generated method stub
		FindPsw findPsw= findPswDao.getByKey(key);
		HibernateUtil.closeSession();
		return findPsw;
	}

	@Override
	public boolean delete(String userId) {
		// TODO Auto-generated method stub
		Session session = null;
		Transaction tx = null;
		boolean result = true;
		try {
			session = HibernateUtil.getCurrentSession();
			tx = session.beginTransaction();
			System.out.println(userId);
			findPswDao.delete(userId);
			tx.commit();
			
		}

		catch (Exception exception) {
			result = false;
		} finally {

			HibernateUtil.closeSession();
		}
		return result;
	}
	public static void main(String[] args) {
		 new FindPswServiceImpl().delete("541234");
	}

}
